package control;

import java.security.Principal;
import java.util.List;

import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import entity.User;
import group.Group;

@Stateless
public class UserManager {

	@PersistenceContext(unitName = "meteoCalPU")
	EntityManager em;

	@Inject
	Principal principal;

	/**
	 * create a new user
	 * 
	 * @param user
	 *            the user
	 */
	public void createUser(User user) {
		user.setGroupName(Group.USERS);
		em.persist(user);
	}

	public String login(String username, String password)
			throws ServletException {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		request.login(username, password);
		return "user/mainPage?faces-redirect=true";
	}

	/**
	 * get the current user
	 * 
	 * @return the user
	 */
	public User getLoggedUser() {
		TypedQuery<User> tq = (TypedQuery<User>) em.createQuery(
				"SELECT u FROM USERS u WHERE  u.username LIKE :username")
				.setParameter("username", principal.getName());
		System.out.println("called the usermanager. user:"
				+ tq.getSingleResult().getUsername());
		return tq.getSingleResult();
	}

	/**
	 * finds all the users
	 * @return the user of the application
	 */
	public List<User> findAll() {
		TypedQuery<User> query = em.createQuery(
				"SELECT u FROM USERS u WHERE u.id != :userid", User.class);
		query.setParameter("userid", this.getLoggedUser().getId());
		return query.getResultList();
	}

	/**
	 * loads the user given the username
	 * 
	 * @param username
	 *            user's username
	 * @return the user
	 */
	public User loadUserByUsername(String username) {
		TypedQuery<User> tq = em.createQuery(
				"SELECT u FROM USERS u WHERE u.username LIKE :username",
				User.class).setParameter("username", username);
		return (User) tq.getSingleResult();
	}

	/**
	 * updates the given user
	 * 
	 * @param u
	 *            the user
	 */
	public void updateUser(User u) {
		em.merge(u);
	}

}